# -*- coding: utf-8 -*-

import cv2
import os
import numpy
from keras.engine.saving import load_model
from musicClassify.project.musicClassify import config,LoadData

if __name__ == '__main__':
    predict_music_dir = config.music_dir_path
    print('---应用数据加载路径:'+ predict_music_dir)
    print('---模型为:'+ config.model_name)

    nameMap = {}
    id = -1
    dirs = os.listdir(predict_music_dir)
    dirs.remove(".DS_Store")  # 删除mac文件夹下的隐藏文件
    dirs = sorted(dirs)
    for dir_item in dirs:
        id = id + 1
        nameMap[id] = dir_item

    # 加载模型
    # model = load_model('saved_models/' + config.model_name)
    model = load_model('saved_models/' + '音乐情绪模型1.h5')

    # 识别
    peoplesDir = os.listdir(predict_music_dir)
    peoplesDir.remove(".DS_Store")  # 删除mac文件夹下的隐藏文件
    peoplesDir = sorted(peoplesDir)
    peopleSize = len(peoplesDir)

    x_train = []
    y_train = []

    acc = 0
    all = 0

    for peopleDir in peoplesDir:
        peoplePath = os.path.abspath(os.path.join(predict_music_dir, peopleDir))
        for picItem in os.listdir(peoplePath):
            picPath = os.path.abspath(os.path.join(peoplePath, picItem))
            if picPath.endswith('.wav'):
                #  [::4]重采样为原来得1/4 数据太大会内存溢出
                data, numchannel = LoadData.Read_WAV(picPath)
                data = data[::11*numchannel]
                # reshape一维升三维
                x_train = numpy.asarray(data).reshape(1000, 4 * config.time, 1)
                classNum = model.predict(numpy.asarray([x_train]))
                if classNum.shape[-1] > 1:
                    result = classNum.argmax(axis=-1)
                else:
                    result = (classNum > 0.5).astype('int32')

                print(picPath, ':::', nameMap[result[0]])
                if peopleDir == nameMap[result[0]]:
                    acc = acc + 1
                all = all + 1
    print('总体准确率：', acc/all)
